package com.wtp.wallpaper.rabbitmq.data;

import com.alibaba.fastjson.JSON;
import com.wtp.wallpaper.es.document.PictureDocument;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class DataChangeEvent implements Serializable {
    private String operationType; // CREATE, BATCH_CREATE, UPDATE, DELETE, BATCH_DELETE
    private Object data; // 实体或ID集合 类型：PictureDocument、List<Long>、List<PictureDocument>

    public Object getData(Class<?> clazz) {
        Object data = getData();
        if (Objects.isNull(data)){
            return null;
        }
        //消费者会把Object类型的对象反序列化为LinkedHashMap，所以这里需要序列化成JSON再反序列化成对象
        return JSON.parseObject(JSON.toJSONString(data), clazz);
    }

    public List getDataList(Class<?> clazz){
        if(data instanceof List){
            return JSON.parseArray(JSON.toJSONString(data), clazz);
        }
        return null;
    }
}